package com.ruoyi.wechat.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.business.domain.OrderManage;
import com.ruoyi.business.mapper.OrderManageMapper;
import com.ruoyi.common.constant.DictConstants;
import com.ruoyi.common.enums.MsgType;
import com.ruoyi.common.enums.RoleKey;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.wechat.domain.MsgRequest;
import com.ruoyi.wechat.service.IAsyncService;
import com.ruoyi.wechat.service.IWechatAppSenderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 功能描述:   创建一个异步线程的接口
 *
 * @Author wanghc
 * @Date 2022/08/22
 * @return
 */
@Service
public class AsyncServiceImpl implements IAsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Autowired
    private IWechatAppSenderService wechatAppSenderService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private OrderManageMapper orderManageMapper;

    /**
     * 功能描述:    异步推送抢单消息
     *
     * @Author wanghc
     * @Date 2022/08/23 01:48
     * @param orderManage
     * @return void
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void executeAsyncSendGrabMsg(OrderManage orderManage) {
        // 工单类型赋值
        orderManage.setOrderTypeShow(DictUtils.getDictLabel(DictConstants.ORDER_TYPE, orderManage.getOrderType()));
        // 工单状态赋值
        orderManage.setOrderStatusShow(DictUtils.getDictLabel(DictConstants.ORDER_STATUS, orderManage.getOrderStatus()));
        logger.info("start executeAsync ---- 待抢单消息通知发送---- order = {}", JSONObject.toJSONString(orderManage));
        // 给所有运维人员发消息
        List<String> openids = sysUserMapper.selectOpenidByRoleKey(RoleKey.OPT.getCode());
        if(CollectionUtil.isNotEmpty(openids)){
            // 过滤集合中的null元素
            List<String> notNullOpenid = openids.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(notNullOpenid)) {
                logger.info("待抢单消息接收人 {}", notNullOpenid.toString());
                MsgRequest msgRequest = MsgRequest.builder()
                        .orderManage(orderManage)
                        .openids(notNullOpenid)
                        .build();
                wechatAppSenderService.sendOrderMessage(msgRequest, MsgType.UNRECEIVE.getCode());
            }
        }
        logger.info("end executeAsync --- 待抢单消息通知结束");
    }

    /**
     * 功能描述:    异步推送接单消息
     *
     * @Author wanghc
     * @Date 2022/08/23 01:48
     * @param orderManage
     * @return void
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void executeAsyncSendReceiveMsg(OrderManage orderManage) {
        orderManage = orderManageMapper.selectOrderManageById(orderManage.getId());
        // 工单类型赋值
        orderManage.setOrderTypeShow(DictUtils.getDictLabel(DictConstants.ORDER_TYPE, orderManage.getOrderType()));
        // 工单状态赋值
        orderManage.setOrderStatusShow(DictUtils.getDictLabel(DictConstants.ORDER_STATUS, orderManage.getOrderStatus()));
        logger.info("start executeAsync ---- 已接单消息通知发送---- order = {}", JSONObject.toJSONString(orderManage));
        // 给报单人发已有人接单通知
        List<String> openids = orderManageMapper.selectOpenidCreateBy(orderManage.getId());
        if(CollectionUtil.isNotEmpty(openids)) {
            // 过滤集合中的null元素
            List<String> notNullOpenid = openids.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(notNullOpenid)) {
                logger.info("已接单消息接收人 {}", notNullOpenid.toString());
                MsgRequest msgRequest = MsgRequest.builder()
                        .orderManage(orderManage)
                        .openids(notNullOpenid)
                        .build();
                wechatAppSenderService.sendOrderMessage(msgRequest, MsgType.RECEIVE.getCode());
            }
        }
        logger.info("end executeAsync --- 已接单消息通知结束");
    }

    /**
     * 功能描述:    异步推送取消消息
     *
     * @Author wanghc
     * @Date 2022/08/23 01:48
     * @param orderManage
     * @return void
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void executeAsyncSendCancelMsg(OrderManage orderManage) {
        orderManage = orderManageMapper.selectOrderManageById(orderManage.getId());
        // 工单类型赋值
        orderManage.setOrderTypeShow(DictUtils.getDictLabel(DictConstants.ORDER_TYPE, orderManage.getOrderType()));
        // 工单状态赋值
        orderManage.setOrderStatusShow(DictUtils.getDictLabel(DictConstants.ORDER_STATUS, orderManage.getOrderStatus()));
        logger.info("start executeAsync ---- 已取消工单通知发送 ---- order = {}", JSONObject.toJSONString(orderManage));
        // 给接单人发取消通知
        List<String> openids = orderManageMapper.selectOpenidReceiverBy(orderManage.getId());
        if(CollectionUtil.isNotEmpty(openids)) {
            // 过滤集合中的null元素
            List<String> notNullOpenid = openids.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(notNullOpenid)) {
                logger.info("已取消工单消息接收人 {}", notNullOpenid.toString());
                MsgRequest msgRequest = MsgRequest.builder()
                        .orderManage(orderManage)
                        .openids(notNullOpenid)
                        .build();
                wechatAppSenderService.sendOrderMessage(msgRequest, MsgType.CANCEL.getCode());
            }
        }
        logger.info("end executeAsync --- 已取消工单通知结束");
    }

    /**
     * 功能描述:    异步推送完工消息
     *
     * @Author wanghc
     * @Date 2022/08/23 01:48
     * @param orderManage
     * @return void
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void executeAsyncSendFinishMsg(OrderManage orderManage) {
        orderManage = orderManageMapper.selectOrderManageById(orderManage.getId());
        // 工单类型赋值
        orderManage.setOrderTypeShow(DictUtils.getDictLabel(DictConstants.ORDER_TYPE, orderManage.getOrderType()));
        // 工单状态赋值
        orderManage.setOrderStatusShow(DictUtils.getDictLabel(DictConstants.ORDER_STATUS, orderManage.getOrderStatus()));
        logger.info("start executeAsync ---- 已完成工单通知发送 ---- order = {}", JSONObject.toJSONString(orderManage));
        // 给报单人发完成通知
        List<String> openids = orderManageMapper.selectOpenidCreateBy(orderManage.getId());
        if(CollectionUtil.isNotEmpty(openids)) {
            // 过滤集合中的null元素
            List<String> notNullOpenid = openids.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(notNullOpenid)) {
                logger.info("已完成工单消息接收人 {}", notNullOpenid.toString());
                MsgRequest msgRequest = MsgRequest.builder()
                        .orderManage(orderManage)
                        .openids(openids)
                        .build();
                wechatAppSenderService.sendOrderMessage(msgRequest, MsgType.FINISHED.getCode());
            }
        }
        logger.info("end executeAsync --- 已完成工单通知结束");
    }


    /**
     * 运维撤单通知报单人
     * @param orderManage
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void executeAsyncSendRevokeMsg(OrderManage orderManage) {
        orderManage = orderManageMapper.selectOrderManageById(orderManage.getId());
        // 工单类型赋值
        orderManage.setOrderTypeShow(DictUtils.getDictLabel(DictConstants.ORDER_TYPE, orderManage.getOrderType()));
        // 工单状态赋值
        orderManage.setOrderStatusShow(DictUtils.getDictLabel(DictConstants.ORDER_STATUS, orderManage.getOrderStatus()));
        logger.info("start executeAsync ---- 已撤单消息通知发送---- order = {}", JSONObject.toJSONString(orderManage));
        // 给报单人发已有人接单通知
        List<String> openids = orderManageMapper.selectOpenidCreateBy(orderManage.getId());
        if(CollectionUtil.isNotEmpty(openids)) {
            // 过滤集合中的null元素
            List<String> notNullOpenid = openids.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(notNullOpenid)) {
                logger.info("已撤单消息接收人 {}", notNullOpenid.toString());
                MsgRequest msgRequest = MsgRequest.builder()
                        .orderManage(orderManage)
                        .openids(notNullOpenid)
                        .build();
                wechatAppSenderService.sendOrderMessage(msgRequest, MsgType.REVOKE.getCode());
            }
        }
        logger.info("end executeAsync --- 已撤单消息通知发送");
    }


}